//
//  ZZSearchChooseController.m
//  Qzone
//
//  Created by zhangxy on 2018/7/5.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZSearchChooseController.h"
#import "ZTextField.h"
#import "ZZHomeTopMenu.h"
#import "ZZShareView.h"
#import "ZZContentCommentController.h"


#import "ZZHomeListCell.h"
#define cellIdentifier @"ZZHomeListCell"

#import "ZZSearchPostCell.h"
#define cellIdentifierTZ @"ZZSearchPostCell"


#import "ZZSearchUserCell.h"
#define cellIdentifierUser  @"ZZSearchUserCell"

@interface ZZSearchChooseController ()<UITextFieldDelegate,ZZTopicCellDelegate>
@property(nonatomic,strong) NSMutableArray *userArray;
@property(nonatomic,strong) NSMutableArray *sucaiArray;
@property(nonatomic,strong) NSMutableArray *tzArray;

// 1、素材 2、帖子， 3 用户
@property(nonatomic,assign) int type;
@property(nonatomic,strong) ZTextField *searchField;

@property(nonatomic,strong)  UITableView *listTable;

@end

@implementation ZZSearchChooseController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationBar];
    
    _userArray = [[NSMutableArray alloc] init];
    _sucaiArray = [[NSMutableArray alloc] init];
    _tzArray = [[NSMutableArray alloc] init];
    
    [self createSearchController];
    
    [self createTableView];

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    [self.navigationController setNavigationBarHidden:YES];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

#pragma mark 搜索视图
- (void)createSearchController
{
    //在tableView存在右侧索引情况下防止搜索框右侧缺少一块
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, ScreenWidth, NavBarHeight + 44);
    [headerView setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    
    _searchField = [[ZTextField alloc] initWithImage:[UIImage imageNamed:@"img_search_copy"] padding:5];
    [_searchField setPlaceholder:@"搜索素材/帖子/用户"];
    [_searchField setFrame:CGRectMake(20, StatusBarHeight, ScreenWidth - 64, 44)];
    [_searchField setBackgroundColor:UIColor.whiteColor];
    _searchField.layer.cornerRadius = 10.0f;
    _searchField.layer.masksToBounds = YES;
    _searchField.clearsOnBeginEditing = YES;
    _searchField.delegate = self;
    [_searchField addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
    [headerView addSubview:_searchField];
    
    [self.view addSubview:headerView];
    
    ZZHomeTopMenu *menu = [[ZZHomeTopMenu alloc] initWithFrame:CGRectMake(20, NavBarHeight, ScreenWidth-40,44) array:@[@"素材",@"帖子",@"用户"] textColor:UIColorFromRGB(TextWhiteColor) checkColor:UIColorFromRGB(TextWhiteColor) result:^(NSInteger tag, NSString *title) {
        self.type = (int)tag;
        //        [self.listTable.header beginRefreshing];
        
        [self loadMoreData];
    }];
    [menu setBackgroundColor:UIColor.clearColor];
    [self.view addSubview:menu];
    
    
    UIButton *btnSearch = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnSearch setImage:[UIImage imageNamed:@"btn_search_close"] forState:0];
    [btnSearch setFrame:CGRectMake(ScreenWidth - 44, StatusBarHeight, 44, 44)];
    btnSearch.tag = 1;
    [btnSearch addTarget:self action:@selector(actionBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnSearch];
}


#pragma mark - 搜索
/*
 每次输入文字都会进行搜索，但只有点击确认之后，才会写入搜索历史
 */
- (void)textFieldValueChanged:(UITextField *)textField
{
    DLog(@"text:%@",textField.text);
    if (textField.text.length > 0) {
        
    }
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self searchAction];
    [self textFieldValueChanged:textField];
    return YES;
}

- (void)searchAction
{
    [_searchField resignFirstResponder];
    
    if (_searchField.text.length == 0) {
        return;
    }
    
    
}

-(void)actionBack{
    [self.navigationController popViewControllerAnimated:YES];
}


/**
 加载更多
 */
-(void)loadMoreData{
    NSString *typeStr = @"sucai";
    if(_type == 2){
        typeStr = @"thread";
    }
    if(_type == 3){
        typeStr = @"user";
    }
    [NetworkUtil POST:API_SearchList parameters:@{@"keyword":convertToString(_searchField.text),@"type":typeStr,@"nav_type":@""} success:^(id responseObject, NSDictionary *dict) {
        NSArray *arr = nil;
        if(self.type == 1){
            arr = dict[@"data"][@"list"][@"avatar"];
        }else{
            arr  = dict[@"data"][@"list"];
        }
        if(arr == nil){
            return;
        }
        if(self.type == 1){
            [self.sucaiArray removeAllObjects];

            for (NSDictionary *item in arr) {
                [self.sucaiArray addObject:[[ZZHomeTopicEntity alloc] initWithDictionary:item]];
            }
        }
        if(self.type == 2){
            for (NSDictionary *item in arr) {
                [self.tzArray addObject:[[ZZHomeTopicEntity alloc] initWithDictionary:item]];
            }
        }
        if(self.type == 3){
            for (NSDictionary *item in arr) {
                [self.userArray addObject:[[User alloc] initWithDictionary:item]];
            }
        }
        
        
        [self.listTable reloadData];
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [PopUtil showMessage:message];
    }];
}


-(void)createTableView{
    _listTable=[self.view createTableView:self cell:cellIdentifier];
    [_listTable setFrame:CGRectMake(0, NavBarHeight + 44, ScreenWidth, ScreenHeight - NavBarHeight - 44)];
    [_listTable registerNib:[UINib nibWithNibName:cellIdentifierUser bundle:nil] forCellReuseIdentifier:cellIdentifierUser];
    [_listTable registerNib:[UINib nibWithNibName:cellIdentifierTZ bundle:nil] forCellReuseIdentifier:cellIdentifierTZ];
    
    [_listTable setBackgroundColor:UIColor.whiteColor];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    
    [self setTableSeparatorInset];
    
    _type = 1;
}



-(void)onCellItemClick:(ZZTopicCellClickType)type obj:(id)senderObj{
    ZZHomeTopicEntity *topic = senderObj;
    
    if(type == ZZClickShare){
        ZZShareView *shareView = [[ZZShareView alloc] initWithShareType:ZZShareTypeTopic vc:self obj:topic];
        [shareView show];
    }
    if(type == ZZClickFav || type == ZZClickStar){
        NSString *typeName = @"fav";
        if(type == ZZClickStar){
            typeName = @"like";
        }
        [NetworkUtil POST:API_cancelvote(topic.nav_type)
               parameters:@{@"id":convertIntToString((int)topic.t_id),
                            @"type":typeName,
                            @"session_uid":[UserUtil getUser].user_id
                            }
                  success:^(id responseObject, NSDictionary *dict) {
                      [PopUtil showMessage:dict[@"msg"]];
                      if(type==ZZClickStar){
                          topic.fav_count = dict[@"data"][@"count"];
                      }else{
                          topic.like_count = dict[@"data"][@"count"];
                      }
                      [self.listTable reloadData];
                  } failure:^(NSError *error, NSString *message) {
                      
                  }];
    }
    if(type == ZZClickComment){
        ZZContentCommentController *vc = [[ZZContentCommentController alloc] init];
        vc.entity = topic;
        [self openPushVC:vc];
    }
    
    if(type == ZZClickOpenVC){
        [self openPushVC:senderObj];
    }
}


#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    if(section == 0){
        
    }
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_type==1){
        return _sucaiArray.count;
    }else if(_type == 2){
        return _tzArray.count;
    }
    return _userArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_type == 1){
        
        ZZHomeListCell *cell = (ZZHomeListCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[ZZHomeListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        cell.delegate = self;
        [cell dataToView:[_sucaiArray objectAtIndex:indexPath.row]];
        return cell;
    }
    if(_type == 2){
        
        ZZSearchPostCell *cell = (ZZSearchPostCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifierTZ];
        if (cell == nil) {
            cell = [[ZZSearchPostCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierTZ];
        }
        cell.delegate = self;
        [cell dataToView:[_tzArray objectAtIndex:indexPath.row]];
        return cell;
    }
    if(_type == 3){
        ZZSearchUserCell *cell = (ZZSearchUserCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifierUser];
        if (cell == nil) {
            cell = [[ZZSearchUserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierUser];
        }
        [cell dataToView:[_userArray objectAtIndex:indexPath.row]];
        return cell;
        
    }
    
    return nil;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //    VipModel *model=[_listArray objectAtIndex:indexPath.row];
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger count = 0;
    if(_type==1){
        count = _sucaiArray.count;
    }else if(_type == 2){
        count = _tzArray.count;
    }else{
        count = _userArray.count;
    }
    if((indexPath.row+1) < count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
